package com.walala.dispatcher.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IP地址
 * @author liuzhenhuan
 *
 */
public class IPUtils {
	private static final Logger logger = LoggerFactory.getLogger(IPUtils.class);
	
	/**
	 * 获取真正IP地址
	 * @return 非循环IP
	 * @throws SocketException
	 * @throws UnknownHostException 
	 */
	public static String getHostIPAddress() throws Exception{
		long traceId=System.currentTimeMillis();
		String localAddress = InetAddress.getLocalHost().getHostAddress();
		logger.info("getHostIPAddress start localAddress:{},traceId:{}",localAddress,traceId);
		if (localAddress!=null&&(!localAddress.startsWith("127"))) {
			logger.info("getHostIPAddress first localAddress:{} is true,traceId:{}",localAddress,traceId);
			return localAddress;
		}
		
		logger.error("getHostIPAddress first localAddress:{} is false,to get real ip second again,traceId:{}",localAddress,traceId);
		for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {  
            NetworkInterface item = e.nextElement();  

            for (InterfaceAddress address : item.getInterfaceAddresses()) {  
                if (address.getAddress() instanceof Inet4Address) {  
                    Inet4Address inet4Address = (Inet4Address) address.getAddress(); 
                    String hostAddress = inet4Address.getHostAddress();
                    
                    boolean isLoopbackAddress = inet4Address.isLoopbackAddress();
                    boolean isSiteLocalAddress = inet4Address.isSiteLocalAddress();
                    
                    logger.info("getHostIPAddress second HostAddress:{},isLinkLocalAddress:{},isLoopbackAddress:{},isMCGlobal:{},isMulticastAddress:{},isSiteLocalAddress:{},traceId:{}",
                    		hostAddress,inet4Address.isLinkLocalAddress(), isLoopbackAddress , inet4Address.isMCGlobal()
                    		, inet4Address.isMulticastAddress(),isSiteLocalAddress,traceId);
                    if ((!isLoopbackAddress)&&(isSiteLocalAddress)) {
                    	logger.info("getHostIPAddress second localAddress:{} is true,traceId:{}",hostAddress,traceId);
						return hostAddress;
					}
                }  
            }  
        }
		return null;
		
	}
	
	
	public static void main(String[] args) throws Exception {
		try {
			System.out.println(getHostIPAddress());
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
